﻿using System;
using System.Reflection;

namespace BorgExt.Tracing
{
    internal static class LoggingActivatorExtensionObjectFactory
    {
        public static object CreateExtensionObject(Extension extension, ExtensionType extensionType)
        {
            var extensionObject = ActivatorExtensionObjectFactory.CreateExtensionObject(extension, extensionType);
            var callTracer = new CallTracer(extensionObject);
            
            return DynamicProxy.DynamicProxy.GetProxy(extensionObject.GetType().GetInterfaces(), callTracer.Trace);
        }

        private class CallTracer
        {
            private readonly object _wrappee;

            public CallTracer(object wrappee)
            {
                _wrappee = wrappee;
            }

            public object Trace(object proxy, MethodInfo method, object[] parameters)
            {
                Console.WriteLine(">>>>> {0}", method.Name);
                return method.Invoke(_wrappee, parameters);
            }
        }
    }
}

